<!DOCTYPE html>
<html lang="zh-CN" xmlns:th="http://www.thymeleaf.org">
<head th:replace="~{fragments/layout :: head('借阅管理')}"></head>
<body>
    <!-- 导航栏 -->
    <nav th:replace="~{fragments/layout :: navbar}"></nav>
    
    <!-- 页面内容 -->
    <div th:replace="~{fragments/layout :: content(~{::main})}">
        <main>
            <div class="d-flex justify-content-between align-items-center mb-4">
                <h2>借阅管理</h2>
                <a href="javascript:history.back()" class="btn btn-outline-secondary">
                    <i class="fas fa-arrow-left me-1"></i> 返回
                </a>
            </div>
            
            <!-- 借阅状态筛选 -->
            <div class="card mb-4">
                <div class="card-body">
                    <!-- 显示成功或错误消息 -->
                    <div th:if="${success}" class="alert alert-success" role="alert">
                        <span th:text="${success}"></span>
                    </div>
                    <div th:if="${error}" class="alert alert-danger" role="alert">
                        <span th:text="${error}"></span>
                    </div>
                    
                    <div class="mb-3 d-flex justify-content-between">
                        <!-- 删除了查看逾期借阅按钮 -->
                        <div>
                            <div class="row mb-3">
                                <div class="col-md-12">
                                    <form th:action="@{/loans/admin/all-loans}" method="get" class="d-flex">
                                        <input type="text" name="keyword" class="form-control me-2" placeholder="搜索用户或图书" th:value="${keyword}">
                                        <button type="submit" class="btn btn-primary">
                                            <i class="bi bi-search"></i> 搜索
                                        </button>
                                    </form>
                                </div>
                            </div>
                        </div>
                    </div>
                    
                    <div class="row">
                        <div class="col-md-3 mb-3 mb-md-0">
                            <div class="nav flex-column nav-pills" role="tablist" aria-orientation="vertical">
                                <a class="nav-link active" id="all-loans-tab" data-bs-toggle="pill" href="#all-loans" role="tab">
                                    <i class="fas fa-list me-2"></i> 所有借阅
                                </a>
                                <a class="nav-link" id="current-loans-tab" data-bs-toggle="pill" href="#current-loans" role="tab">
                                    <i class="fas fa-bookmark me-2"></i> 当前借阅
                                </a>
                                <a class="nav-link" id="returned-loans-tab" data-bs-toggle="pill" href="#returned-loans" role="tab">
                                    <i class="fas fa-check-circle me-2"></i> 已归还
                                </a>
                                <!-- 删除了逾期借阅链接 -->
                            </div>
                        </div>
                        <div class="col-md-9">
                            <div class="tab-content">
                                <!-- 所有借阅 -->
                                <div class="tab-pane fade show active" id="all-loans" role="tabpanel">
                                    <div class="d-flex justify-content-between align-items-center mb-3">
                                        <h5 class="mb-0">所有借阅记录</h5>
                                        <form class="d-flex" method="get" th:action="@{/loans/admin/all-loans}">
                                            <input class="form-control me-2" type="search" placeholder="搜索用户或图书" name="keyword">
                                            <button class="btn btn-outline-primary" type="submit">搜索</button>
                                        </form>
                                    </div>
                                    
                                    <div class="table-responsive">
                                        <table class="table table-striped table-hover">
                                            <thead>
                                                <tr>
                                                    <th>ID</th>
                                                    <th>用户</th>
                                                    <th>图书</th>
                                                    <th>借阅日期</th>
                                                    <th>应还日期</th>
                                                    <th>实际归还日期</th>
                                                    <th>状态</th>
                                                    <th>操作</th>
                                                </tr>
                                            </thead>
                                            <tbody>
                                                <tr th:each="loan : ${loans}">
                                                    <td th:text="${loan.id}">1</td>
                                                    <td>
                                                        <a th:href="@{/admin/users/{id}(id=${loan.user.id})}" th:text="${loan.user.name}">用户名</a>
                                                    </td>
                                                    <td>
                                                        <a th:href="@{/books/view/{id}(id=${loan.book.id})}" th:text="${loan.book.title}">图书标题</a>
                                                    </td>
                                                    <td th:text="${#temporals.format(loan.borrowDate, 'yyyy-MM-dd')}">2023-01-01</td>
                                                    <td th:text="${#temporals.format(loan.dueDate, 'yyyy-MM-dd')}">2023-02-01</td>
                                                    <td th:text="${loan.returnDate != null ? #temporals.format(loan.returnDate, 'yyyy-MM-dd') : '-'}">-</td>
                                                    <td>
                                                        <span class="badge bg-primary" th:if="${loan.status == 'BORROWED'}">借阅中</span>
                                                        <span class="badge bg-success" th:if="${loan.status == 'RETURNED'}">已归还</span>
                                                        <span class="badge bg-danger" th:if="${loan.status == 'OVERDUE'}">逾期</span>
                                                    </td>
                                                    <td>
                                                        <div class="btn-group btn-group-sm">
                                                            <a th:href="@{/books/view/{id}(id=${loan.book.id})}" class="btn btn-outline-primary">
                                                                <i class="fas fa-info-circle"></i>
                                                            </a>
                                                            <!-- 归还操作 -->
                                                        <button th:if="${loan.status != 'RETURNED'}" type="button" class="btn btn-success return-book-btn" 
                                                                th:data-loan-id="${loan.id}" 
                                                                th:data-book-title="${loan.book.title}"
                                                                th:data-borrow-date="${#temporals.format(loan.borrowDate, 'yyyy-MM-dd')}"
                                                                th:data-due-date="${#temporals.format(loan.dueDate, 'yyyy-MM-dd')}">
                                                            <i class="fas fa-undo"></i>
                                                        </button>
                                                        </div>
                                                        
                                                        <!-- 不再为每个借阅项创建单独的模态框 -->
                                                    </td>
                                                </tr>
                                                <tr th:if="${#lists.isEmpty(loans)}">
                                                    <td colspan="8" class="text-center py-3">暂无借阅记录</td>
                                                </tr>
                                            </tbody>
                                        </table>
                                    </div>
                                    
                                    <!-- 分页 -->
                                    <nav aria-label="Page navigation" th:if="${totalPages > 0}">
                                        <ul class="pagination justify-content-center">
                                            <li class="page-item" th:classappend="${currentPage == 0 ? 'disabled' : ''}">
                                                <a class="page-link" th:href="@{/loans/admin/all-loans(page=${currentPage - 1}, keyword=${keyword})}">上一页</a>
                                            </li>
                                            <li class="page-item" th:each="i : ${#numbers.sequence(0, totalPages - 1)}" 
                                                th:classappend="${currentPage == i ? 'active' : ''}">
                                                <a class="page-link" th:href="@{/loans/admin/all-loans(page=${i}, keyword=${keyword})}" th:text="${i + 1}">1</a>
                                            </li>
                                            <li class="page-item" th:classappend="${currentPage + 1 >= totalPages ? 'disabled' : ''}">
                                                <a class="page-link" th:href="@{/loans/admin/all-loans(page=${currentPage + 1}, keyword=${keyword})}">下一页</a>
                                            </li>
                                        </ul>
                                    </nav>
                                </div>
                                
                                <!-- 当前借阅 & 已归还 标签页的内容在实际页面中可以通过JavaScript从API获取 -->
                                <div class="tab-pane fade" id="current-loans" role="tabpanel">
                                    <div class="text-center py-5">
                                        <p>正在加载当前借阅数据...</p>
                                    </div>
                                </div>
                                
                                <div class="tab-pane fade" id="returned-loans" role="tabpanel">
                                    <div class="text-center py-5">
                                        <p>正在加载已归还数据...</p>
                                    </div>
                                </div>
                            </div>
                        </div>
                    </div>
                </div>
            </div>
        </main>
    </div>
    
    <!-- 页脚 -->
    <footer th:replace="~{fragments/layout :: footer}"></footer>
    
    <!-- 脚本 -->
    <div th:replace="~{fragments/layout :: scripts}"></div>
    
    <!-- 全局归还确认模态框 -->
    <div class="modal fade" id="globalReturnModal" tabindex="-1" aria-labelledby="globalReturnModalLabel" aria-hidden="true">
        <div class="modal-dialog modal-dialog-centered">
            <div class="modal-content">
                <div class="modal-header bg-light">
                    <h5 class="modal-title" id="globalReturnModalLabel">确认归还图书</h5>
                    <button type="button" class="btn-close" data-bs-dismiss="modal" aria-label="Close"></button>
                </div>
                <div class="modal-body">
                    <div class="text-center mb-3">
                        <i class="fas fa-book text-primary" style="font-size: 2rem;"></i>
                    </div>
                    <div class="alert alert-info">
                        <p class="mb-0">您确定要归还以下图书吗？</p>
                    </div>
                    <div class="card mb-3">
                        <div class="card-body">
                            <h5 class="card-title" id="returnBookTitle">图书标题</h5>
                            <p class="card-text">借阅日期: <span id="returnBorrowDate">2023-01-01</span></p>
                            <p class="card-text">应还日期: <span id="returnDueDate">2023-01-15</span></p>
                        </div>
                    </div>
                </div>
                <div class="modal-footer justify-content-between">
                    <button type="button" class="btn btn-secondary" data-bs-dismiss="modal">
                        <i class="fas fa-times me-1"></i> 取消
                    </button>
                    <form id="globalReturnForm" th:action="@{/loans/admin/return}" method="post">
                        <input type="hidden" id="returnLoanId" name="loanId" value="">
                        <button type="submit" class="btn btn-success">
                            <i class="fas fa-check me-1"></i> 确认归还
                        </button>
                    </form>
                </div>
            </div>
        </div>
    </div>

    <!-- 借阅管理专用脚本 -->
    <script>
    document.addEventListener('DOMContentLoaded', function() {
        // 全局模态框对象
        const returnModal = new bootstrap.Modal(document.getElementById('globalReturnModal'));
        
        // 归还图书按钮点击事件
        const returnButtons = document.querySelectorAll('.return-book-btn');
        returnButtons.forEach(button => {
            button.addEventListener('click', function(e) {
                e.preventDefault();
                // 获取按钮上的数据
                const loanId = this.getAttribute('data-loan-id');
                const bookTitle = this.getAttribute('data-book-title');
                const borrowDate = this.getAttribute('data-borrow-date');
                const dueDate = this.getAttribute('data-due-date');
                
                // 设置模态框中的数据
                document.getElementById('returnBookTitle').textContent = bookTitle;
                document.getElementById('returnBorrowDate').textContent = borrowDate;
                document.getElementById('returnDueDate').textContent = dueDate;
                document.getElementById('returnLoanId').value = loanId;
                
                // 显示模态框
                returnModal.show();
            });
        });
        
        // 处理归还表单提交
        const returnForm = document.getElementById('globalReturnForm');
        returnForm.addEventListener('submit', function(e) {
            e.preventDefault();
            
            // 禁用按钮防止重复提交
            const submitButton = this.querySelector('button[type="submit"]');
            const originalText = submitButton.innerHTML;
            submitButton.disabled = true;
            submitButton.innerHTML = '<i class="fas fa-spinner fa-spin"></i> 处理中...';
            
            const formData = new FormData(this);
            const modalBody = document.querySelector('#globalReturnModal .modal-body');
            
            // 发送归还请求
            fetch('/loans/admin/return', {
                method: 'POST',
                body: formData,
                headers: {
                    'X-Requested-With': 'XMLHttpRequest'
                }
            })
            .then(response => {
                if (response.ok) {
                    // 创建成功消息
                    const successAlert = document.createElement('div');
                    successAlert.className = 'alert alert-success mt-3';
                    successAlert.innerHTML = '<i class="fas fa-check-circle me-2"></i>图书已成功归还！';
                    
                    // 替换模态框内容
                    modalBody.innerHTML = '';
                    modalBody.appendChild(successAlert);
                    
                    // 替换按钮
                    const modalFooter = document.querySelector('#globalReturnModal .modal-footer');
                    modalFooter.innerHTML = '<button type="button" class="btn btn-primary" onclick="window.location.reload()">关闭并刷新</button>';
                    
                    // 1.5秒后自动刷新页面
                    setTimeout(() => {
                        window.location.reload();
                    }, 1500);
                } else {
                    throw new Error('归还操作失败');
                }
            })
            .catch(error => {
                // 恢复按钮状态
                submitButton.disabled = false;
                submitButton.innerHTML = originalText;
                
                // 显示错误消息
                const errorAlert = document.createElement('div');
                errorAlert.className = 'alert alert-danger mt-3';
                errorAlert.innerHTML = '<i class="fas fa-exclamation-triangle me-2"></i>错误: ' + error.message;
                
                modalBody.appendChild(errorAlert);
            });
        });
    });
    </script>
</body>
</html>
